<style>
.toast{
  z-index: 9999 !important;
}
/* 设置按钮 */
.login > .signinbtn .mint-button {
  position: fixed;
  right: 0.5rem;
  top: 0.5rem;
}

/* 登录按钮 */
.login > .loginbtn > .mint-button {
  background-color: #007d65;
  position: fixed;
  top: 5rem;
  left: 50%;
  transform: translateX(-50%);
  width: 6rem;
  height: 6rem;
  border-radius: 100%;
  box-shadow: 1px 1px 22px 2px;
  color: wheat;
}

/* 导航按钮 */
.login .mint-tabbar{
background-image: url();
}
.login .mint-tabbar,.login .alltag {
  background-color: #ffffff;

  margin: 0 6px;

}
.login .tagbtn {
  bottom: 24rem;

}
.login .tagbtn2{
  bottom: 15rem;
}
.login .alltag {
  height: 12rem;
  margin-top: 20rem;
  border-radius: 1rem;
}

/* 登录注册弹窗 */
.login .mint-popup {
  height: 100%;
  width: 100%;
  /* background-color: rgb(199, 13, 13); */
}
/* 登陆下面的文字 */
.login .mint-popup .mint-header {
  background-color: #007d65;
}
.loginspan{
  position: absolute;
  top: 185px;
    left: 27%;
}
body{
  background-color: #f6f6f6;
}
/* 更多服务 */
.all-sdiv{
  position: absolute;
  top: 49%;
  left: 18px;
}
.all-span{
  font-size: 20px;
  font-weight: bold;
  font-family:Microsoft JhengHei;
}
.login .tagbtn3 {
    bottom: 11rem;
}
.mint-tabbar > .mint-tab-item.is-selected{
    color: #000;
}

/* 登录页样式 */
.login .input {
  
      background-color: rgba(red, green, blue, 0) ;
}
.login .input .mint-cell {
  
      background-color: rgba(red, green, blue, 0) ;
}
</style>

<template>
  <div class="login">
    <!-- 设置按钮 -->
    <div class="signinbtn">
      <mt-button @click.native="popSignIn" size="small">注册</mt-button>
    </div>

    <!-- 登录按钮 -->
    <div class="loginbtn">
      <mt-button @click.native="popLogin" size="small">登录</mt-button>
    </div>
  <!-- 登陆下面的文字 -->
    <div class="loginspan">
      <span class="login-span">登陆后，随时收藏、关注</span>
    </div>    
    <!-- 功能栏开始 -->

    <section class="alltag">
         <!-- 更多服务 -->
      <div class="all-sdiv">
        <span class="all-span">更多服务</span>
      </div>

            <mt-tabbar v-model="selected" class="tagbtn" @click.native="pleaseLogin">
        <mt-tab-item id="tab1">
          <img slot="icon" src="../assets/img/星星.png" />
          历史
        </mt-tab-item>
        <mt-tab-item id="tab2">
          <img slot="icon" src="../assets/img/时间.png" />
          收藏
        </mt-tab-item>
        <mt-tab-item id="tab3">
          <img slot="icon" src="../assets/img/分享.png" />
          分享
        </mt-tab-item>
        <mt-tab-item id="tab4">
          <!-- 客服 -->
          <img slot="icon" src="../assets/img/托管.png" />
          托管
        </mt-tab-item>
      </mt-tabbar>

      <mt-tabbar v-model="selected" class="tagbtn2" @click.native="pleaseLogin">
        <mt-tab-item id="tab5">
          <img slot="icon" src="../assets/img/客服.png" />
          客服
        </mt-tab-item>
        <mt-tab-item id="tab6">
          <img slot="icon" src="../assets/img/优选.png" />
          优选
        </mt-tab-item>
        <mt-tab-item id="tab7">
          <img slot="icon" src="../assets/img/订单.png" />
          订单
        </mt-tab-item>
        <mt-tab-item id="tab8">
          <img slot="icon" src="../assets/img/咨询.png" />
          资讯
        </mt-tab-item>
      </mt-tabbar>

        <!-- 第三块 -->
    <mt-tabbar v-model="selected" class="tagbtn3" @click.native="pleaseLogin">
      <mt-tab-item id="tab9">
        <img slot="icon" src="../assets/img/预约.png" />
        预约
      </mt-tab-item>
      <mt-tab-item id="tab10">
        <img slot="icon" src="../assets/img/我的帖子.png" />
        我的帖子
      </mt-tab-item>
      <mt-tab-item id="tab11">
        <img slot="icon" src="../assets/img/论坛.png" />
        论坛
      </mt-tab-item>
      <mt-tab-item id="tab12">
        <img slot="icon" src="../assets/img/勋章.png" />
        勋章
      </mt-tab-item>
    </mt-tabbar>
    </section>


    <!-- 功能栏结束 -->

    <!-- 登录页弹窗开始 -->
    <mt-popup class="popLogin" v-model="isPopLogin" position="bottom">
      <!-- 头部开始 -->
      <mt-header title="登录">
        <router-link to="/login" slot="left">
          <mt-button icon="back" @click="popLogin"></mt-button>
        </router-link>
      </mt-header>
      <!-- 头部结束 -->

      <!-- 主体开始 -->
      <main class="input">
        <!-- 用户名 -->
        <mt-field
          label="用户名"
          placeholder="请输入用户名"
          v-model="username"
        ></mt-field>
        <!-- 输入密码 -->
        <mt-field
          label="输入密码"
          placeholder="请输入密码"
          type="password"
          v-model="password"
        ></mt-field>

        <!-- 输入验证码 -->
        <mt-field label="验证码" v-model="captcha">
          <img :src="imgCode" height="45px" width="100px" @click="otherImg" />
        </mt-field>
        <mt-button size="large" type="danger" @click="submit('login')"
          >登录</mt-button
        >
      </main>
      <!-- 主体结束 -->
    </mt-popup>
    <!-- 登录页弹窗结束 -->

    <!-- 注册页弹窗开始 -->
    <mt-popup class="popSignin" v-model="isPopSignIn" position="bottom">
      <!-- 头部开始 -->
      <mt-header title="注册">
        <router-link to="/login" slot="left">
          <mt-button icon="back" @click="popSignIn"></mt-button>
        </router-link>
      </mt-header>
      <!-- 头部结束 -->

      <!-- 主体开始 -->
      <main class="input">
        <!-- 用户名 -->
        <mt-field
          label="用户名"
          placeholder="请输入用户名"
          v-model="username"
        ></mt-field>

        <!-- 邮箱 -->
        <mt-field
          label="邮箱"
          placeholder="请输入邮箱"
          type="email"
          v-model="email"
          v-show="signIn"
        ></mt-field>

        <!-- 输入密码 -->
        <mt-field
          label="输入密码"
          placeholder="请输入密码"
          type="password"
          v-model="password"
        ></mt-field>

        <!-- 再次输入密码 -->
        <mt-field
          label="确认密码"
          placeholder="请输入密码"
          type="password"
          v-model="password2"
          v-show="signIn"
        ></mt-field>

        <!-- 输入验证码 -->
        <mt-field label="验证码" v-model="captcha">
          <img :src="imgCode" height="45px" width="100px" @click="otherImg" />
        </mt-field>
        <!-- 提交按钮 -->
        <mt-button size="large" type="danger" @click="submit('signIn')"
          >注册</mt-button
        >
      </main>
      <!-- 主体结束 -->
    </mt-popup>
    <!-- 注册页弹窗结束 -->
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 功能栏集火状态
      selected: "",
      
      // 用户信息：将来验证登录成功后从服务器获取该数据
      resultData: {
        //userName: "",

     
      },
      // 显示的图片url
      imgCode: "",
      // 验证码图片库
      imgs: ["a", "b", "c", "d", "e"],
      // 登录注册信息

      username: "",
      usernameState: "",
      password: "",
      passwordState: "",
      password2: "",
      password2State: "",
      email: "",
      emailState: "",
      // 输入的验证码，在服务器将图片名所拥有的值跟该验证码进行核对
      captcha: "",
      captchaState: "",
      // 需要传给服务器的图片名
      imgName: "",
      // 图片验证:该数据必须存放在数据库
      imgVerify: {
        a: 1234,
        b: 4252,
        c: 5372,
        d: 7585,
        e: 4226,
      },
      // 判断是登录还是注册
      signIn: true,
      // 登录注册弹窗状态
      isPopLogin: false,
      isPopSignIn: false,
      // 标签数据
      tabbarData1: [
        {
          id: "#",
          text: "收藏",
        },
        {
          id: "#",
          text: "历史",
        },
      ],
      tabbarData2: [
        {
          id: "#",
          text: "签到",
        },
        {
          id: "#",
          text: "消息",
        },
      ],
    };
  },
  methods: {
    checkEmail(){
      let exp = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (exp.test(this.email)) {
        this.emailState = "";
        return true;
      } else {
        this.emailState = "请输入正确格式邮箱";
        /*以数字字母开头，中间可以是多个数字字母下划线或"-"，然后是"@"符号，后面数字字母，然后是"."符号加2-4个字母结尾*/
        return false;
      }
    },
  checkUsername() {
      let exp = /[\u4e00-\u9fa5_a-zA-Z0-9_]{2,10}/;
      if (exp.test(this.username)) {
        this.usernameState = "";
        return true;
      } else {
        this.usernameState = "请输入2~10位用户名";
        return false;
      }
    },
    checkEPassword() {
      if (this.password2 == this.password) {
        this.password2State = "";
        return true;
      } else {
        this.password2State = "两次密码不一致";
        return false;
      }
    },
    checkPassword() {
      let exp = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W]{6,18}$/;
      if (exp.test(this.password)) {
        this.passwordState = "";
        return true;
      } else {
        this.passwordState = "密码必须包含字母和数字，且在6~18位之间";
        return false;
      }
    },
    link() {},
    setSelected() {},
    //提交表单
    submit(type) {
      /* 
      1.根据传入参数判断是登录还是注册操作
      2.登录操作流程：
        1）用户填写账户和密码
        2）点击按钮生成一个图片验证码（在本地获取一个图片验证码，一分钟有效，可以重复获取）
        3）点击提交后：将账户、密码、验证码、验证码图片信息、一同发送给服务器（post加密请求）
        4）服务器先验证验证码和图片信息是否能对得上，再验证账户和密码是否对得上
        5）当验证成功，将该账号相关信息全都发送给客户端（获取响应request.data）
        6) vuex将该用户信息存储起来，并根据用户信息渲染页面
        7）当vuex完成页面更新后，显示登录成功并跳转到/User页面
      
      3.注册操作流程：
      
      
      */
      if (type == "login") {
        /* 
        在该处写异步post请求，并将返回的值储存到resultData中。
        */
       console.log(this.imgName);
       if(this.checkUsername()&&this.checkPassword()){
         console.log("验证成功")
            this.axios.post('/log/login',`username=${this.username}&password=${this.password}&imgName=${this.imgName}&captcha=${this.captcha}`)
            .then(res=>{
                if(res.data.code==200){
                    this.$toast('登录成功');
                    this.resultData=res.data.result;
                    console.log(this.resultData);
                     if (this.resultData) {
          // 将用户值储存到vuex的dataUser中。 注意：这里该使用mutations修改值
          /*console.log(this.resultData);*/
          this.$store.state.dataUser = this.resultData;
          
          // 将用户数据储存到内容中
          sessionStorage.setItem("resultData", JSON.stringify(this.resultData));

          //执行登录并跳转到用户页

          console.log("登录成功");

          // ss.setItem('isLogin',1)
          // 该位置当登录成功只需要自动跳转回用户界面即可
          // 注意：还需要将弹窗状态修改为false
          this.$store.commit("setPopUpLogin");
          this.$router.push({
            name: "user",
          });
        } else {
          console.log("失败dddd");
        }
                    /*this.$store.commit('loginSuccess',res.data.result);
                    let ss = window.sessionStorage;
                    ss.setItem('isLogin',1);
                    ss.setItem('userInfo',JSON.stringify(res.data.result));
                    this.$router.push('/');*/
                }else{
                    this.$toast({
                        message: `登陆失败${res.data.message}`,
                        position: 'bottom',
                        durdation: 3000,
                        className: "toast"
                    })
                }
              })
            }
        // 判断是否接受到用户数据,如果接到就赋值给vuex的用户数据，并保存到缓存中
       
      } else {
        /* 
          该处写注册post请求
          如果成功则跳转到登录页面
        */
        if (
          this.checkUsername() &&
          this.checkEmail() &&
          this.checkPassword()&&
          this.checkEPassword()
        ) {

          console.log("开始发送注册请求")
          this.axios
            .post("/reg/login", `username=${this.username}&password=${this.password}&email=${this.email}&imgName=${this.imgName}&captcha=${this.captcha}`)
            .then((res) => {
              if (res.data.code == 200) {
                this.$toast({
                  message: `注册成功`,
                  position: "bottom",
                  duration: 2000,
                  className: "toast"
                });
                this.isPopSignIn = !this.isPopSignIn;
                this.isPopLogin = !this.isPopLogin;
                //this.$router.push('/login')
              } else {
                this.$toast({
                  message: `注册失败${res.data.message}`,
                  position: "bottom",
                  duration: 2000,
                  className: "toast"
                });
              }
            });
        } else {
          if(this.usernameState !== ""){
            this.$toast({
                  message: this.usernameState,
                  duration: 2000,
                  className: "toast"
                });
          }else if(this.emailState !== ""){
            this.$toast({
                  message: this.emailState,
                  duration: 2000,
                  className: "toast"
                });
          }
          else if(this.passwordState !== ""){
            this.$toast({
                  message: this.passwordState,
                  duration: 2000,
                  className: "toast"
                });
          }else{
            this.$toast({
                  message: this.password2State,
                  duration: 2000,
                  className: "toast"
                });
          }
        }
      }
    },

    // 未登录提示

    pleaseLogin() {
      if (!this.$store.state.dataUser) {
        this.$toast({
          message: "请先登录",
          // position: 'bottom',
          duration: 2000,
        });
      } else {
      }
    },
    // 切换验证码图片
    otherImg() {
      //随机获取图片
      var num = Math.round(Math.random() * 4);
      this.imgCode = require(`../assets/img/imgCode/${this.imgs[num]}.png`);
      // 需要将当前图片的名字传给服务器验证
      this.imgName = this.imgs[num];
    },

    // 登录注册函数
    popLogin() {
      this.isPopLogin = !this.isPopLogin;
    },
    popSignIn() {
      this.isPopSignIn = !this.isPopSignIn;
    },
  },
  mounted() {
    // 随机挂载验证码
    //this.imgCode = require("../assets/img/imgCode/b.png");
    var num = Math.round(Math.random() * 4);
      this.imgCode = require(`../assets/img/imgCode/${this.imgs[num]}.png`);
      // 需要将当前图片的名字传给服务器验证
      this.imgName = this.imgs[num];
      // console.log(this.imgName);
  },
};
</script>
